import packetCode from './webPacketCode.js'
import webScoket from './webSocket.js'
import base from '../config.js';
const EventDispatcher = function() {
	this.listeners = {}
}
let eventDispatcher
let user = uni.getStorageSync("userInfo")
const WEBIM = {
	serverUrl: base.socketUrl + "/" + user.id,
	server: null,
	heartCheck: true,
	isReconnection: true,
	options: null,
	//初始化
	initSocket: function(packet) {
		 WEBIM.options = {
			packet,
		 	url: WEBIM.serverUrl,
		 	success(res) {
			},
		 	fail(err) {
			}
		 }
		 
		 eventDispatcher = new EventDispatcher();
		 
		 WEBIM.server = new webScoket({
		 	heartCheck: true,
		 	isReconnection: true,
		 });
		 WEBIM.server.initWebSocket(WEBIM.options);
		 
		 WEBIM.server.onReceivedMsg(event => {
		 	let packet = JSON.parse(event.data);
			console.log(packet)
		 	let command = packet.command;
			if(command == 5){
				// 接受到发送来的消息
				uni.$emit("receiveMsg",packet)
			}
		 	eventDispatcher.dispatchEvent(command, (packet))
		 	eventDispatcher.removeListener(command, (packet))
		 });
		 WEBIM.server.onNetworkChange(WEBIM.options);
		 WEBIM.server.onSocketClosed(WEBIM.options);
	},
	//断开连接
	disconnect: function(e) {
		WEBIM.server.closeWebSocket()
	},
	//是否连接
	isConnect: function() {
		return WEBIM.server._isLogin;
	},
	// 进行重连
	reConnection(){
		return new Promise((resolve, reject) => {
			WEBIM.server._isLogin = false;
			if (WEBIM.server._isReconnection) {
				//console.log('网络中断，尝试重连')
				WEBIM.options = {
					url: WEBIM.serverUrl,
					success(res) {
						//console.log(JSON.stringify(res),'连接成功')
						resolve(res);
					},
					fail(err) {
						//console.log(JSON.stringify(err),'重连失败')
						reject(err);
					}
				}
				WEBIM.server._reConnect(WEBIM.options)
				//console.log('【websocket】尝试手动重连')
			}
		});
	},
	// 登录
	login: (userId, groupIds, func) =>{
		let packet1 = {
			userId,
			groupIds,
			version: 1,
			command: 1
		}
		WEBIM.server.sendWebSocketMsg({
			packet: packet1,
			data: packet1,
			success(res) {
				console.log(JSON.stringify(res))
				eventDispatcher.addListener('2',func);
			},
			fail(err) {
			}
		});
	},
	// 心跳检测
	heartTest: (func) => {
		let packet = {
			version: 1,
			command: 17
		}
		eventDispatcher.addListener('18', func)
		sendWebSocketMsg(packet).catch(err=>{
			uni.showToast({
				icon:'none',
				title:'Webscoket is closed heartTest'
			})
		})
	},
	
	// 发送消息
	sendMessage: (params, func) => {
		params.version = 1;
		params.command = 3;
		eventDispatcher.addListener('4', func);
		sendWebSocketMsg(params).catch(err=>{
			uni.showToast({
				icon:'none',
				title:'Webscoket is closed sendMessage'
			})
		})
	},
	//注销用户通道
	logout: (func) => {
		let packet = {
			userId:store.state.user.operId,
			version: 1,
			command: 5
		}
		eventDispatcher.addListener('6', func);
		sendWebSocketMsg(packet).catch(err=>{
			uni.showToast({
				icon:'none',
				title:'Webscoket is closed logout'
			})
		})
	}
}

let sendWebSocketMsg = (p) => {
	return new Promise((resolve, reject) => {
		WEBIM.server.sendWebSocketMsg({
			data: p,
			success(res) {
				resolve(res)
			},
			fail(err) {
				reject(err)
			}
		});
	});
}


function toJSON(packet) {
	return JSON.parse(JSON.stringify(packet))
}

EventDispatcher.prototype.addListener = function(eventKey, fun, context) {
	let list = []
	this.listeners[eventKey] = list
	let listener = {
		func: fun,
		context: context
	}
	list.push(listener)
	return listener
}

EventDispatcher.prototype.removeListener = function(eventKey, fun, context) {
	let list = this.listeners[eventKey]
	if (list !== undefined) {
		let size = list.length
		for (let i = 0; i < size; i++) {
			let listener = list[i]
			if (listener.func === fun && listener.context === context) {
				list.splice(i, 1)
				return
			}
		}
	}
}

EventDispatcher.prototype.dispatchEvent = function(eventKey, event) {
	let list = this.listeners[eventKey]
	if (list !== undefined) {
		let size = list.length
		for (let i = 0; i < size; i++) {
			let listener = list[i]
			let fun = listener.func
			let context = listener.context
			if (context != null) {
				fun.call(context, event)
			} else {
				fun(event)
			}
		}
	}
}



export default WEBIM
